import axios from 'axios'
import qs from 'qs'
import { URL,caiwuURL } from './url'
import { getLoca } from '../assets/js/common'
import Vue from 'vue'

axios.defaults.withCredentials = true
// axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

export default async function (url = '', data = {}, type = 'POST', urlAll = null, config = {} ) {

	url = urlAll != null ? url : URL + url

	data = qs.stringify(data);
	if( type == 'GET') data = {params: data}
	type = type.toUpperCase()

	var ajax = type == 'POST' ? axios.post(url, data,config) : axios.get(url, data,config);

	var promise = new Promise( ( resolve, rej) => {
		//检查cookis 是否存在
		if( !getLoca('userInfo') ){
			var act = data.split('&')[0].split('=')[1]
			if(act != 'login' && act != 'getMobileCode' && act != 'editpwd'){
				// alert('请先登录！')
				window.location.href = '/#/login';
				return ;
			}
		}
		// console.log(getLoca('userInfo') == '')

        ajax = ajax.then(res => res.data)
            .then( res => {
				if( res.url && res.url === '/tologin'){
					window.location.href='/#/login'
					return ;
				}
                if(res.code == 1){
                    resolve(res)
                    return res
                }else{
					Vue.$vux.toast.show({
						text:res.msg,
						width:'auto',
						type:'text',
						position:'top'
					})
                    throw new Error('状态码不是 1， 禁止代码执行了')
				}
            })
            .catch(e => {
                console.error(e)
            })

    }).catch( e => {
        console.log(e)
    })

	return promise
}

